package net.chrisrichardson.ec2deployer.applications;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*
import org.apache.commons.logging.*
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.util.FileBasedTemplate
import net.chrisrichardson.ec2deployer.core.Application;
import net.chrisrichardson.ec2deployer.applications.TomcatServer
import net.chrisrichardson.ec2deployer.cluster.AppServerTier
import net.chrisrichardson.ec2deployer.cluster.ClusterSpec
import net.chrisrichardson.ec2deployer.util.FileUtil
import net.chrisrichardson.ec2deployer.core.S3Synchronizer

class ApacheServer extends Application {

    Log logger = LogFactory.getLog(getClass())
    AppServerTier appServerTier
    int port = 80
    String apacheConfDir = "/etc/httpd/conf"
    String apacheConfDDir = "/etc/httpd/conf.d"
    String apacheBinDir = "/usr/sbin"

    ClusterSpec spec

    protected ApacheServer() {}
    
    public ApacheServer(EC2Server host, AppServerTier appServerTier, ClusterSpec spec) {
        super(host)
        this.appServerTier = appServerTier
        this.spec = spec
    }

    List<TomcatServer> getTomcats() {
       appServerTier.tomcats
    }

    def configure() {
        if (spec.extraHttpConf) {
            exec "cat > $apacheConfDDir/extras.conf", spec.extraHttpConf
        }

        writeFile fileName: "$apacheConfDir/httpd.conf", templateName: "/templates/httpd.conf", templateArgs:  [tomcats: tomcats]
        writeFile fileName: "$apacheConfDDir/cluster.conf", templateName: "/templates/cluster.conf", templateArgs:  [tomcats: tomcats]
        if (spec.sslRequired) {
            exec "yum -y install mod_ssl"
            writeFile fileName: "$apacheConfDDir/ssl.conf", templateName: "/templates/ssl.conf", templateArgs:  [tomcats: tomcats]
            host.scp FileUtil.cygdrive(spec.sslKeyFile), "$apacheConfDir/my.key"
            host.scp FileUtil.cygdrive(spec.sslCertFile), "$apacheConfDir/my.cert"
            exec "chmod 0400 $apacheConfDir/my.key"
            exec "chmod 0400 $apacheConfDir/my.cert"
        }
        if (spec.staticContentSupplied)
            installStaticContent()
        exec "$apacheBinDir/apachectl restart"
        waitForHttp path: tomcats[0].actualContexts[0]
        if (spec.sslRequired)
        waitForHttp scheme: "https", path: tomcats[0].actualContexts[0]
        if (spec.staticContentSupplied)
            waitForHttp path: ""
    }

     public void ping(String url) {
        def client = new HttpClient()
        def fullUrl = "http://${host.publicDnsName}${url}"
        logger.debug(fullUrl)
        def getMethod = new GetMethod(fullUrl)
        def statusCode = client.executeMethod(getMethod)
        assert statusCode == 200

    }

    // Copied from WebApp
    
    String getSubDirectory() {
        int n = Math.max(spec.staticContentPath.lastIndexOf('/'), spec.staticContentPath.lastIndexOf('\\'))
        if (n >= 0)
            return "/" + spec.staticContentPath.substring(n + 1)
        else
            return "/" + spec.staticContentPath
    }

    void installStaticContent() {
        S3Synchronizer synchronizer = new S3Synchronizer(host.awsProperties)
        synchronizer.uploadToS3( [spec.staticContentPath], spec.bucketPrefix, spec.staticContentBucket)
        synchronizer.downloadFromS3(host, spec.bucketPrefix, spec.staticContentBucket, "/var/tmp/staticcontent")
        host.ssh("rsync --del -u -v -r  /var/tmp/staticcontent${subDirectory}/ /var/www/html")
    }

    void curl(String path, String method) {
        def params = method == "POST" ? "--data \"nothing=something\" " : ""
        host.ssh("curl $params \"http://localhost${path}\"")
    }
}